package com.example.demo;


import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.example.bean.ModelMsg;
import com.example.service.weiChatService;
import com.example.util.SignUtil;
import com.example.util.httpSendUtil;

import net.sf.json.JSONObject;

@RestController
public class weiChatController {
	@Autowired
	private weiChatService wcs;
	@RequestMapping(value="weiChatInit")
	public  String weiChatInit(HttpServletRequest request, HttpServletResponse response) throws Exception{
		  // 微信加密签名  
        String signature = request.getParameter("signature");  
        // 时间戳  
        String timestamp = request.getParameter("timestamp");  
        // 随机数  
        String nonce = request.getParameter("nonce");  
        // 随机字符串  
        String echostr = request.getParameter("echostr");  
        String result="";
        if(null!=echostr&&!"".equals(echostr)){
        	// 通过检验signature对请求进行校验，若校验成功则原样返回echostr，表示接入成功，否则接入失败  
            if (SignUtil.checkSignature(signature, timestamp, nonce)) {  
            	result= echostr;  
            } 
        }else{
        	result=wcs.dealEvent(request,response);
        }
         
        return result;
	}
	@RequestMapping(value="sendTemPlate")
	public String sendTemPlate(HttpServletRequest request, HttpServletResponse response){
		String templetId="iAH2fVTYGWrjhd_urY5AWLtvMByWq0w-LcbZn69YIzM";
		String toUser="oMKRcwU8SAkki8_G3oPezk2dBYHo";
		String topColor="#FF0000";
		String url="http://spe.cumminsgps.cn";
		String postUrl="https://api.weixin.qq.com/cgi-bin/message/template/send?access_token="+wcs.getAccess_token();
		Map<String ,Object>finalResult=new HashMap<String,Object>();
		finalResult.put("touser", toUser);
		finalResult.put("template_id", templetId);
		finalResult.put("url", url);
		finalResult.put("topcolor", topColor);
		Map<String,Object>data=new HashMap<String,Object>();
		data.put("first",new ModelMsg("尊敬的高客户，您今天有10台车发生高油耗提醒，请点击“详情”查看明细",topColor));
		data.put("keyword1",new ModelMsg("20171124-20171125",topColor));
		data.put("keyword2",new ModelMsg("行驶里程大于1500Km",topColor));
		data.put("keyword3",new ModelMsg("大于35L/100Km",topColor));
		data.put("keyword4",new ModelMsg("150台",topColor));
		data.put("keyword5",new ModelMsg("68台",topColor));
		data.put("remark",new ModelMsg("请及时做出措施",topColor));
		finalResult.put("data",data);
		JSONObject json=JSONObject.fromObject(finalResult);
		String resultCode=httpSendUtil.sendPost(postUrl, json.toString());
		return resultCode;
	}
}
